﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace Pdf2epub.UI
{
    public class ImageFileEditor : Xceed.Wpf.Toolkit.PropertyGrid.Editors.ITypeEditor
    {
        private Label m_Label;

        public FrameworkElement ResolveEditor(Xceed.Wpf.Toolkit.PropertyGrid.PropertyItem propertyItem)
        {
            DockPanel dp = new DockPanel { LastChildFill = true };
            Button bt = new Button { Content = "..." };
            bt.Click += OnButtonClick;
            DockPanel.SetDock(bt, Dock.Right);
            dp.Children.Add(bt);
            m_Label = new Label { Content = "" };
            dp.Children.Add(m_Label);

            //create the binding from the bound property item to the editor
            Binding binding = new Binding("Value")
                                  {
                                      Source = propertyItem,
                                      ValidatesOnExceptions = true,
                                      ValidatesOnDataErrors = true,
                                      Mode = propertyItem.IsReadOnly ? BindingMode.OneWay : BindingMode.TwoWay
                                  }; //bind to the Value property of the PropertyItem
            BindingOperations.SetBinding(m_Label, ContentControl.ContentProperty, binding);
            return dp;
        }

        private void OnButtonClick(Object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog openFile = new Microsoft.Win32.OpenFileDialog();
            openFile.Filter = "Image files (*.jpg, *.png, *.gif) |*.jpg;*.png;*.gif";
            if (openFile.ShowDialog() == true)
            {
                m_Label.Content = openFile.FileName;
                BindingExpression be = m_Label.GetBindingExpression(ContentControl.ContentProperty);
                if (be != null)
                    be.UpdateSource();
            }
        }
    }
}